import { useAPIUtils } from "@/components/APIUtilsProvider";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import {
  Badge,
  Box,
  Button,
  Card,
  Grid,
  Group,
  Image,
  MultiSelect,
  SimpleGrid,
  Text,
  Title,
} from "@mantine/core";
import { IconCheck } from "@tabler/icons-react";
import { useState } from "react";
import { useParams } from "react-router-dom";

export default function PartyAUserDetails() {
  return (
    <PageLayout title={"內部用户详情"}>
      <Grid w="96%">
        <Grid.Col span={7}>
          <Basics />
        </Grid.Col>
        <Grid.Col span={3} offset={2}>
          <SideContent />
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

const Descriptions = ({ title, data }) => {
  return (
    <Box padding="md">
      {title && (
        <Title order={6} mb={"lg"}>
          {title}
        </Title>
      )}
      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </>
        ))}
      </Grid>
    </Box>
  );
};

function Basics() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const userQuery = tanstackQuery(`/api/admin/users/${id}`);

  if (!userQuery.data) {
    return <></>;
  }

  const user = userQuery.data;

  const descriptionsData = [
    { label: "昵称", value: user.user.nickname, block: true },
    {
      label: "权限",
      value: <UserRestAuthoritiesDisplay user={user} />,
      block: true,
    },
  ];
  return <Descriptions title={`用户ID: ${id}`} data={descriptionsData} />;
}

function SideContent() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const userQuery = tanstackQuery(`/api/admin/users/${id}`);

  const changePassword = async (newPassword) => {
    await restPUT(`/api/admin/users/${id}/password`, { newPassword });
  };

  const changeNickname = async (nickname) => {
    await restPUT(`/api/admin/users/${id}/nickname`, { nickname });
  };

  if (!userQuery.data) {
    return <></>;
  }

  const user = userQuery.data;
  return (
    <>
      <Card shadow="sm" padding="lg" radius="md" withBorder>
        <Card.Section>
          <Image src={user.user.meta.avatar} h={400} alt="" />
        </Card.Section>
        <RenderIf auth="PartyAUserManagement">
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入新密码，8位以上的数字和字母组合",
                onConfirm: changePassword,
              })
            }
          >
            修改密码
          </Button>
          <Button
            color="blue"
            fullWidth
            mt="md"
            radius="md"
            onClick={() =>
              moreModals.openPromptModal({
                title: "请输入新昵称，注意不要出现非法信息",
                onConfirm: changeNickname,
              })
            }
          >
            修改昵称
          </Button>
        </RenderIf>
      </Card>
    </>
  );
}

function UserRestAuthoritiesDisplay({ user }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();
  const allQuery = tanstackQuery(`/api/admin/restAuthorities`);

  const [editing, setEditing] = useState(false);

  if (!allQuery.data) {
    return "loading...";
  }

  const options = allQuery.data.reduce((acc, item) => {
    acc[item.name] = item.config.label;
    return acc;
  }, {});

  return (
    <>
      {!editing && (
        <>
          <SimpleGrid cols={3}>
            {user.userRestAuthorities
              .map((v) => options[v] || v)
              .map((v, i) => (
                <Badge radius={"xs"} color={"blue"} key={i}>
                  {v}
                </Badge>
              ))}
          </SimpleGrid>
          <RenderIf auth="PartyAUserManagement">
            <Button
              size="xs"
              w={"100"}
              mt={"lg"}
              variant="light"
              onClick={() => setEditing(true)}
            >
              权限变更
            </Button>
          </RenderIf>
        </>
      )}

      {editing && (
        <AuthEdit
          user={user}
          data={allQuery.data}
          close={() => setEditing(false)}
        />
      )}
    </>
  );
}

function AuthEdit({ data, user, close }) {
  const selectData = data.map((item) => ({
    value: item.name,
    label: item.config.label,
    description: item.config.description,
  }));

  const [value, setValue] = useState(user.userRestAuthorities);

  const { tanstackInvalidate, restPUT } = useAPIUtils();

  const change = async () => {
    await restPUT(`/api/admin/users/partyA/${user.id}/restAuthorities`, value);
    tanstackInvalidate(`/api/admin/users/${user.id}`);
    close();
  };

  let iconProps = {
    stroke: 1.5,
    color: "currentColor",
    opacity: 0.6,
    size: 18,
  };

  const renderOption = ({ option, checked }) => (
    <Group justify="flex-start" gap={"2"}>
      {checked && (
        <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />
      )}
      {`${option.label} - ${option.description}`}
    </Group>
  );

  return (
    <>
      <MultiSelect
        clearable
        placeholder="Pick value"
        data={selectData}
        value={value}
        renderOption={renderOption}
        onChange={setValue}
      />
      <Group justify="flex-end">
        <Button onClick={close} mt={"md"} size="xs" variant="light">
          取消
        </Button>
        <Button onClick={change} mt={"md"} size="xs">
          提交
        </Button>
      </Group>
    </>
  );
}
